package com.dongdongshop.service.impl.order;

import com.dongdongshop.mapper.*;
import com.dongdongshop.pojo.address.TbAddress;
import com.dongdongshop.pojo.areas.TbAreas;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.cities.TbCities;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.pojo.order.TbOrder;
import com.dongdongshop.pojo.order_item.TbOrderItem;
import com.dongdongshop.pojo.provinces.TbProvinces;
import com.dongdongshop.service.order.OrderService;
import com.dongdongshop.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbAddressMapper tbAddressMapper;
    @Autowired
    private TbProvincesMapper tbProvincesMapper;
    @Autowired
    private TbCitiesMapper tbCitiesMapper;
    @Autowired
    private TbAreasMapper tbAreasMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    //购物车Key
    @Value("${cart.key}")
    String cartKey;
    //订单key
    @Value("${order.key}")
    String orderKey;
    //添加订单
    @Override
    @Transactional
    public String insertOrder(Long addressId, String pay, List<Cart> cartList) {
        List<TbOrder> orderList = new ArrayList<>();
        TbAddress tbAddress = tbAddressMapper.selectByPrimaryKey(addressId);
        TbProvinces provinces = tbProvincesMapper.getProbincesByProId(tbAddress.getProvinceId());
        TbCities cityByCityId = tbCitiesMapper.getCityByCityId(tbAddress.getCityId());
        TbAreas areaByAreaId = tbAreasMapper.getAreaByAreaId(tbAddress.getTownId());
        Long orderParentL = idWorker.nextId();
        String orderParent = orderParentL.toString();
        for (Cart cart : cartList) {
            TbOrder tbOrder = new TbOrder();
            long orderId = idWorker.nextId();
            tbOrder.setOrderParent(orderParent);
            tbOrder.setOrderId(orderId);
            tbOrder.setPaymentType(pay);
            tbOrder.setStatus("1");
            tbOrder.setCreateTime(new Date());
            tbOrder.setUserId(tbAddress.getUserId());
            tbOrder.setReceiverAreaName(provinces.getProvince()+cityByCityId.getCity()+areaByAreaId.getArea()+tbAddress.getAddress());
            tbOrder.setReceiverMobile(tbAddress.getMobile());
            tbOrder.setReceiver(tbAddress.getContact());
            tbOrder.setSourceType("1");
            tbOrder.setSellerId(cart.getSellerId());
            BigDecimal bigDecimal = new BigDecimal(0L);
            //将oorderItem添加到list中
            List<TbOrderItem> orderItems = new ArrayList<>();
            //将信息保存到数据库中
            for (TbOrderItem orderItem : cart.getOrderItemList()) {
                orderItem.setOrderId(orderId);
                tbOrderItemMapper.insertSelective(orderItem);
                bigDecimal = bigDecimal.add(orderItem.getPrice());
                orderItems.add(orderItem);
            }
            tbOrder.setPayment(bigDecimal);
            //将orderItems添加到orderList中
            tbOrderMapper.insertSelective(tbOrder);
            tbOrder.setOrderItemList(orderItems);
            orderList.add(tbOrder);

        }
        //将订单信息保存到Redis中
        getTbOrderFrom(orderList.get(0).getUserId(),orderList);
        redisTemplate.delete(cartKey);
        return orderParent;
    }
    //交易成功修改状态
    @Override
    public void updateStatusToHave(String out_trade_no,String trade_no) {
        tbOrderMapper.updateStatusToHave(out_trade_no,trade_no,new Date());
        List<TbOrder> orderList = tbOrderMapper.selectOrderByOrderParent(out_trade_no);
        updateStatusAndAliPay(out_trade_no,trade_no,orderList.get(0).getUserId());

    }
    //查询订单
    @Override
    public List<TbOrder> listOrder(String s, String username) {
        List<TbOrder> orderListFromRedis = (List<TbOrder>) redisTemplate.opsForHash().get(orderKey, username);
        if (orderListFromRedis==null){
            return null;
        }
        List<TbOrder> orderList = new ArrayList<>();
        for (TbOrder order : orderListFromRedis) {
            if (s.equals(order.getStatus())){
                orderList.add(order);
            }
        }
        return orderList;
    }
    //退款修改状态
    @Override
    public void updateStatusToRefund(String out_trade_no, String trade_no,String out_request_no) {
        tbOrderMapper.updateStatusToRefund(Long.getLong(out_request_no));
        List<TbOrder> orderList = tbOrderMapper.selectOrderByOrderParent(out_trade_no);
        updateStatusAndAliPayToRefund(Long.getLong(out_request_no),orderList.get(0).getUserId());
    }

    @Override
    public List<TbOrderItem> listOrderByOrderParent(String out_trade_no) {
        List<TbOrder> orderList = tbOrderMapper.selectOrderByOrderParent(out_trade_no);
        List<TbOrderItem> list = new ArrayList<>();
        for (TbOrder order : orderList) {

            List<TbOrderItem> orderItemList = tbOrderItemMapper.listOrderItemByOrderId(order.getOrderId());

            list.addAll(orderItemList);
        }
        return list;
    }


    private void updateStatusAndAliPayToRefund(Long out_request_no, String username) {
        List<TbOrder> orderListFromRedis = (List<TbOrder>) redisTemplate.opsForHash().get(orderKey, username);
        for (TbOrder order : orderListFromRedis) {
            if (out_request_no==order.getOrderId()){
                order.setStatus("6");
                order.setUpdateTime(new Date());
            }
        }
        redisTemplate.opsForHash().put(orderKey,username,orderListFromRedis);
    }


    //将购物信息添加到Redis中
    private void getTbOrderFrom(String username,List<TbOrder> orderList){

        List<TbOrder> orderListFromRedis = (List<TbOrder>) redisTemplate.opsForHash().get(orderKey, username);
        if (orderListFromRedis == null){
            redisTemplate.opsForHash().put(orderKey,username,orderList);
        }else {
            for (TbOrder order : orderListFromRedis) {
                orderList.add(order);
            }
            redisTemplate.opsForHash().put(orderKey,username,orderList);
        }
    }
    //修改Redis中的status
    private void updateStatusAndAliPay(String orderParent,String aliPayId,String username){
        List<TbOrder> orderListFromRedis = (List<TbOrder>) redisTemplate.opsForHash().get(orderKey, username);
        for (TbOrder order : orderListFromRedis) {
            if (orderParent.equals(order.getOrderParent())){
                order.setStatus("3");
                order.setUpdateTime(new Date());
                order.setAlipayId(aliPayId);
            }
        }
        redisTemplate.opsForHash().put(orderKey,username,orderListFromRedis);
    }
}
